package Region.socket;

import Region.DatabaseManager;
import Region.LogManager;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.sql.SQLException;
import java.util.ArrayList;

//实现与client通信的线程
public class ClientThread implements Runnable{
    private Socket socket;
    private boolean isRunning = false;

    public BufferedReader input = null;
    public PrintWriter output = null;
    private DatabaseManager dataBaseManager;
    private LogManager logManager;
    private MasterSocketManager masterSocketManager;
    private int copy_port;

    public ClientThread(int copy_port, Socket socket, MasterSocketManager masterSocketManager, DatabaseManager dataBaseManager, LogManager logManager)
            throws IOException {
        this.copy_port = copy_port;
        this.masterSocketManager = masterSocketManager;
        this.socket = socket;
        this.logManager = logManager;
        this.dataBaseManager = dataBaseManager;
        this.isRunning = true;
        // 基于Socket建立输入输出流
        this.input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        this.output = new PrintWriter(socket.getOutputStream(), true);
        System.out.println("服务端建立了新的客户端子线程：" + socket.getPort());
    }

    @Override
    public void run() {
        System.out.println("服务器监听客户端消息中" + socket.getInetAddress());
        String command;
        try {
            while (isRunning) {
                Thread.sleep(1000);
                command = input.readLine();
                System.out.println(command);

                int kuohao_index = command.indexOf(']');
                String title = command.substring(0,kuohao_index+1);
                String sql = command.substring(kuohao_index+1);

                if (title.equals("<C2R>[6]")) {
                    System.out.println("接收的的命令：" + command);
                    String result = this.selectProcess(sql);
                    //将结果返回client
                    sendToClient(result);
                }else if(title.equals("<C2R>[12]")){
                    System.out.println("接收的的命令：" + command);
                    String result = this.commandProcess(sql);
                    //将结果返回client
                    sendToClient(result);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String selectProcess(String sql) throws SQLException, IOException {
        return dataBaseManager.selectSQL(sql);
    }

    private String commandProcess(String sql) throws SQLException, IOException, InterruptedException {
        //第一个逗号之前是表名
        int tableNameIndex = sql.indexOf(",");
        String tableName = sql.substring(0, tableNameIndex);
        String sql_sentence = sql.substring(tableNameIndex+1);

        //最后一个逗号之后是一个ip
        int first_ip_index = sql_sentence.lastIndexOf(',');
        String first_ip="";
        if(first_ip_index!=sql_sentence.length()-1) first_ip=sql_sentence.substring(first_ip_index+1);
        sql_sentence=sql_sentence.substring(0,first_ip_index);

        //倒数第二个逗号之后到最后一个逗号之间是一个ip
        int second_ip_index = sql_sentence.lastIndexOf(',');
        String second_ip=sql_sentence.substring(second_ip_index+1);
        sql_sentence=sql_sentence.substring(0,second_ip_index);

        String title = sql_sentence.substring(0, sql_sentence.indexOf(" "));
        if(title.equals("drop")) masterSocketManager.sendToMaster("<R2M>[9]"+tableName);

//        System.out.println(first_ip);
//        System.out.println(second_ip);
//        System.out.println(sql_sentence);

        String result;
        String sql_result = dataBaseManager.updateSQL(sql_sentence);
        if(Character.isDigit(sql_result.charAt(0))) result = "Successful, "+sql_result+" lines have been changed\n";
        else result = sql_result+"\n";

        if(Character.isDigit(sql_result.charAt(0))){
            //对数据库进行修改，需要修改日志
            logManager.addLog(tableName,sql_sentence);
        }

        try {
            if(!first_ip.isEmpty()) {
                Socket first_socket = new Socket(first_ip, copy_port);
                PrintWriter first_output = new PrintWriter(first_socket.getOutputStream());
                first_output.println(tableName+","+sql_sentence);
                first_output.flush();
                System.out.println("主从复制2成功");
            }
            Socket second_socket = new Socket(second_ip, copy_port);
            PrintWriter second_output = new PrintWriter(second_socket.getOutputStream());
            second_output.println(tableName+","+sql_sentence);
            second_output.flush();
            System.out.println("主从复制成功");

        }catch (Exception e){
            System.out.println(e);
        }

        return result;
    }

    private void sendToClient(String result){
        output.println("<R2C>[6]" + result);
        output.flush();
    }
}
